package com.st.swagger.service;

import com.st.swagger.entity.Review;
import com.st.swagger.mapper.ReviewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    /**
     * 获取所有评论
     */
    public List<Review> getAllReviews() {
        return reviewMapper.findAll();
    }

    /**
     * 根据商品 ID 获取评论
     */
    public List<Review> getReviewsByProductId(Long productId) {
        return reviewMapper.findByProductId(productId);
    }

    /**
     * 根据评论 ID 获取评论
     */
    public Review getReviewById(Long id) {
        Review review = reviewMapper.findById(id);
        if (review == null) {
            throw new RuntimeException("评论不存在");
        }
        return review;
    }

    /**
     * 添加新评论
     */
    public Review createReview(Review review) {
        review.setReviewTime(LocalDateTime.now());
        reviewMapper.insertReview(review);
        return review;
    }

    /**
     * 更新评论
     */
    public Review updateReview(Long id, Review review) {
        Review existingReview = reviewMapper.findById(id);
        if (existingReview == null) {
            throw new RuntimeException("评论不存在");
        }
        review.setId(id);
        reviewMapper.updateReview(review);
        return review;
    }

    /**
     * 删除评论
     */
    public void deleteReview(Long id) {
        Review existingReview = reviewMapper.findById(id);
        if (existingReview == null) {
            throw new RuntimeException("评论不存在");
        }
        reviewMapper.deleteReview(id);
    }
}

